#include "JSON.h"
#include "WString.h"


bool JsonParser::parserMachine(char c){
	if(' '==c)
		return true;

	switch(state_){
			case READY:
				if(c=='{'){
					state_ = READING;
					listener_.onBegin();
				}
				return true;
			case READING:
				if(c=='"'){
					state_ = NAME;
					return true;
				}
				break;
			case NEXT_OR_END:
				if(c==','){
					state_ = READING;
					return true;
				}
				if(c=='}'){
					listener_.onEnd();
					reset();
					return true;
				}
				break;
			case NAME:
				if(c=='"'){
					currentTag_[currentReadPos_++]=0;
					state_ = COLON;
					currentReadPos_ = 0;
					return true;
				} else {
					currentTag_[currentReadPos_++]=c;
					return true;
				}
				break;
			case COLON:
				if(':'){
					state_ = BEGIN_VALUE;
					return true;
				}
				break;
			case BEGIN_VALUE:
				if(c=='"'){
					state_ = VALUE;
					return true;
				}
				break;
			case VALUE:
				if(c=='"'){
					currentValue_[currentReadPos_++]=0;
					if(!listener_.onItem(currentTag_, currentValue_)){
						//discard message - client don't want to parse further
						reset();
						return false;
					}
					state_ = NEXT_OR_END;
					currentReadPos_ = 0;
					return true;
				} else {
					currentValue_[currentReadPos_++]=c;
					return true;
				}
				break;
			default:
				break;

	}
	listener_.onParseError();
	reset();
	return false;
}
void JsonParser::reset(){
	state_ = READY;
	currentReadPos_ = 0;
}
JsonParser::JsonParser(JsonContentListener& l): currentReadPos_ (0), state_(READY), listener_(l) {
	memset(currentTag_, 0, JSON_ITEM_LENGTH);
	memset(currentValue_, 0, JSON_ITEM_LENGTH);
}
void JsonParser::parse(const String& msg)  {
	for(unsigned int i = 0; i < msg.length(); ++i){
		if(!parserMachine(msg[i]))
			break;
	}
	if(READY!=state_){
		listener_.onParseError();
		reset();
	}
}